import 'package:flutter/material.dart';

class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('DataTable'),
        leading: const Icon(Icons.menu),
        elevation: 0,
        centerTitle: true,
        actions: const [Icon(Icons.settings)],
      ),
      body: const UserList(),
    );
  }
}

class UserList extends StatefulWidget {
  const UserList({Key? key}) : super(key: key);

  @override
  _UserListState createState() => _UserListState();
}

class User {
  final String name;
  final int age;
  bool selected;

  User(this.name, this.age, {this.selected = false});
}

class _UserListState extends State<UserList> {
  final List<User> data = [
    User('张三', 18),
    User('张三丰', 218, selected: true),
    User('张翠山', 30),
    User('张无忌', 60),
  ];

  List<DataRow> _getUserRows() {
    return data.asMap().entries.map((entry) {
      final index = entry.key;
      final user = entry.value;
      return DataRow(
        selected: user.selected,
        onSelectChanged: (selected) {
          setState(() {
            user.selected = selected ?? false;
          });
        },
        cells: [
          DataCell(Text(user.name)),
          DataCell(Text('${user.age}')),
          const DataCell(Text('男')),
          const DataCell(Text('---')),
        ],
      );
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: DataTable(
        columns: const [
          DataColumn(label: Text('姓名')),
          DataColumn(label: Text('年龄')),
          DataColumn(label: Text('性别')),
          DataColumn(label: Text('简介')),
        ],
        rows: _getUserRows(),
      ),
    );
  }
}